define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'subject/subjectattachment/index',
                    add_url: 'subject/subjectattachment/add',
                    edit_url: 'subject/subjectattachment/edit',
                    del_url: 'subject/subjectattachment/del',
                    multi_url: 'subject/subjectattachment/multi',
                    table: 'subject_attachment'
                }
            });

            var table = $("#table");


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        { field: 'state', checkbox: true },
                        { field: 'id', title: "ID" },
                        { field: 'unique_id', title: "全局搜索ID" },
                        { field: 'subject_class', title: "科目分类", align: 'left' },
                        { field: 'admin_id', title: "管理员", visible: false, addClass: "selectpage", extend: "data-source='auth/admin/index' data-field='nickname'" },
                        { field: 'user_id', title: "用户", visible: false, addClass: "selectpage", extend: "data-source='user/user/index' data-field='nickname'" },
                        { field: 'filename', title: "文件名", sortable: true, formatter: Controller.api.formatter.filename, operate: 'like' },
                        { field: 'filename_new', title: "附件名称", sortable: true, formatter: Controller.api.formatter.filename, operate: 'like' },
                        { field: 'preview', title: "预览", formatter: Controller.api.formatter.thumb, operate: false },
                        { field: 'url', title: "保存地址", formatter: Controller.api.formatter.url, visible: false },
                        {
                            field: 'filesize', title: "文件大小", operate: 'BETWEEN', sortable: true, formatter: function (value, row, index) {
                                var size = parseFloat(value);
                                var i = Math.floor(Math.log(size) / Math.log(1024));
                                return (size / Math.pow(1024, i)).toFixed(i < 2 ? 0 : 2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
                            }
                        },
                        { field: 'imagetype', title: "文件类型", sortable: true, formatter: Table.api.formatter.search, operate: 'like' },
                        { field: 'show_position', title: "显示位置", sortable: true, formatter: Controller.api.formatter.show_position },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            width: 150
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
            });

            //给添加按钮添加`data-area`属性
            $(".btn-add").data("area", ["98%", "100%"]);

            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone,.btn-edit").data("area", ["98%", "100%"]);
            });

            // 绑定过滤事件
            $('.filter-type ul li a', table.closest(".panel-intro")).on('click', function (e) {
                $(this).closest("ul").find("li").removeClass("active");
                $(this).closest("li").addClass("active");
                var field = 'mimetype';
                var value = $(this).data("value") || '';
                var object = $("[name='" + field + "']", table.closest(".bootstrap-table").find(".commonsearch-table"));
                if (object.prop('tagName') == "SELECT") {
                    $("option[value='" + value + "']", object).prop("selected", true);
                } else {
                    object.val(value);
                }
                table.trigger("uncheckbox");
                table.bootstrapTable('refresh', { pageNumber: 1 });
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 附件归类
            $(document).on('click', '.btn-classify', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Classify'),
                    content: Template("typetpl", {}),
                    btn: [__('OK')],
                    yes: function (index, layero) {
                        var category = $("select[name='category']", layero).val();
                        Fast.api.ajax({
                            url: "subject/subjectattachment/classify",
                            type: "post",
                            data: { category: category, ids: ids.join(',') },
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });

        },
        add: function () {
            //上传完成后刷新父窗口
            $(".faupload").data("upload-complete", function (files) {
                // setTimeout(function () {
                //     window.parent.$(".btn-refresh").trigger("click");
                // }, 100);
            });
            // 获取上传类别
            $("#faupload-third,#faupload-third-chunking").data("category", function (file) {
                return $("#category-third").val();
            });
            // 获取上传类别
            $("#faupload-local,#faupload-local-chunking").data("category", function (file) {
                return $("#category-local").val();
            });

            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                //选择分类
                $(".select-subject-class-id").click(function () {
                    var subject_class_ids = $('#subject-class-ids').val();
                    Fast.api.open('subject/subjectclass/pop?ids=' + subject_class_ids, '选择分类', {
                        "area": ["50%", "90%"],
                        callback: function (rows) {
                            if (rows.length > 0) {
                                var ids = ",";
                                var titles = ",";
                                var unique_ids = ",";
                                rows.forEach(row => {
                                    ids += row["id"] + ",";

                                    row["title"] = row["title"].replace(/<[^>]+>/g, '');
                                    row["title"] = row["title"].replace(/&nbsp;/g, '');
                                    titles += row["title"] + ",";

                                    unique_ids += row["unique_id"] + ",";
                                });
                                $("#selected-tips").html(titles);
                                $('#subject-class-ids').val(ids);
                                $('#subject-class-titles').val(titles);
                                $('#subject-class-unique-ids').val(unique_ids);
                            } else {
                                $("#selected-tips").html("您没有选择任何分类!");
                                $('#subject-class-ids').val("");
                                $('#subject-class-titles').val("");
                                $('#subject-class-unique-ids').val("");
                            }
                        }
                    });
                });

                //科目分类选择框变化，引起知识点和实验的选择框跟随改变
                $("#subject_class_id > select").change(function () {
                    var classids = $(this).val();
                    console.log("subject_class_ids", classids);
                    if (classids.length == 0) {
                        return;
                    }
                    var ids_str = "";
                    for (var i = 0; i < classids.length; i++) {
                        ids_str += classids[i] + ",";
                    }
                    //知识点
                    $.ajax({
                        url: 'subject/subjectattachment/selectknowledge',
                        type: 'post',
                        data: { "classids": ids_str },
                        success: function (response) {
                            $('#knowledge').html(response);
                        }
                    });
                    //实验
                    $.ajax({
                        url: 'subject/subjectattachment/selectexperiment',
                        type: 'post',
                        data: { "classids": ids_str },
                        success: function (response) {
                            $('#experiment').html(response);
                        }
                    });
                });

                //只有付费下载才出现"储值"
                $("#right_type input[type='radio']").click(function () {
                    var val = $(this).val();
                    console.log("val", val);
                    if (val == 2) {
                        $("#form-group-fee").show();
                    } else {
                        $("#form-group-fee").hide();
                    }
                });

                //只有空中教室、高三艺考才出现"显示位置"
                $("#function_model_form_group input[type='checkbox']").click(function () {

                    var is_classroom_checked = false;
                    var is_gaosan_checked = false;
                    $("#function_model_form_group input[type='checkbox']:checked").each(function () {
                        var id = $(this).attr("id");
                        if (id == "is_classroom") {
                            is_classroom_checked = true;
                        }
                        if (id == "is_gaosan") {
                            is_gaosan_checked = true;
                        }
                    });

                    //空中教室、高三艺考都没有选中
                    if (!is_classroom_checked && !is_gaosan_checked) {
                        $("#show_position_form_group").hide();
                    } else {
                        $("#show_position_form_group").show();
                    }
                });

                //影音区下拉框变化，影音区选项是否出现
                $("#library_video > select").change(function () {
                    var library_video = $(this).val();
                    if(library_video>0){
                        $("#video_form_group").show();
                    }else{
                        $("#video_form_group").hide();
                    }
                });

            },
            formatter: {
                thumb: function (value, row, index) {
                    var html = '';
                    if (row.mimetype.indexOf("image") > -1) {
                        html = '<a href="' + row.fullurl + '" target="_blank"><img src="' + row.fullurl + row.thumb_style + '" alt="" style="max-height:60px;max-width:120px"></a>';
                    } else {
                        html = '<a href="' + row.fullurl + '" target="_blank"><img src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + row.imagetype + '" alt="" style="max-height:90px;max-width:120px"></a>';
                    }
                    return '<div style="width:120px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + html + '</div>';
                },
                url: function (value, row, index) {
                    return '<a href="' + row.fullurl + '" target="_blank" class="label bg-green">' + row.url + '</a>';
                },
                filename: function (value, row, index) {
                    return '<div style="width:200px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + Table.api.formatter.search.call(this, value, row, index) + '</div>';
                },
                mimetype: function (value, row, index) {
                    return '<div style="width:80px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + Table.api.formatter.search.call(this, value, row, index) + '</div>';
                },
                show_position: function (value, row, index) {
                    if (value == "1") {
                        return "右";
                    }
                    if (value == "2") {
                        return "授";
                    }
                    if (value == "3") {
                        return "听";
                    }
                },
            },
            fetchZhangjie: function () {

                $('[name="row[subject_class_id]"]').change(function () {
                    // alert("test");
                    var class_id = $(this).val(); // 获取父级选中的值
                    if (class_id) {
                        // 使用Ajax获取子级列表数据
                        $.ajax({
                            url: 'subject/subjectattachment/selectZhangjie', // 服务器端的URL
                            type: 'post',
                            data: { class_id: class_id }, // 发送到服务器的数据
                            success: function (response) {
                                $('#zhangjie_select').html(response);
                            }
                        });
                    } else {
                        // 如果没有选中任何父级选项，清空子级选项
                        $('#zhangjie_select').html("");
                    }
                });
            }
        }
    };
    return Controller;
});
